package gang.org.springframework.framework.io;

import gang.org.springframework.framework.util.GangStringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author gang.chen
 * @description
 * @Date 2021/7/30 13:12
 */
public class GangUrlResource extends GangAbstractFileResolvingResource{

    private final URI uri;
    private final URL url;

    private volatile URL cleanedUrl;

    public GangUrlResource(URI uri) throws MalformedURLException {
        this.uri = uri;
        this.url =uri.toURL();
    }

    public GangUrlResource(URL url) {
        this.uri = null;
        this.url = url;
    }

    @Override
    public InputStream getInputStream() {
        //TODO
        try {
            URLConnection con = this.url.openConnection();
            return con.getInputStream();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public URL getURL()  {
        return this.url;
    }

    @Override
    public File getFile() {
        if (false){
            //TODO
            return null;
        }else {
            return super.getFile();
        }
    }

    @Override
    public String getDescription() {
        return "URL [" + this.url + "]";
    }

    @Override
    public int hashCode() {
        //TODO
        return getCleanedUrl().hashCode();
    }

    private URL getCleanedUrl(){

        URL cleanedUrl = this.cleanedUrl;
        if (cleanedUrl != null){
            //TODO
        }

        cleanedUrl = getCleanedUrl(this.url, (this.uri != null ? this.uri : this.url).toString());

        this.cleanedUrl = cleanedUrl;

        return cleanedUrl;
    }

    private static URL getCleanedUrl(URL originalUrl, String originalPath){
        String cleanedPath = GangStringUtils.cleanPath(originalPath);
        if (false){
            //TODO
        }
        return originalUrl;
    }
}
